package com.yifei.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.yifei.model.entity.auth.SysUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: Security框架工具类
 * @Author: yiFei
 * @date: 2022/2/16 23:08
 */
public class SecurityUtil {

    private SecurityUtil() {

    }

    /**
     * 获取当前登录人信息
     *
     * @return
     */
    public static SysUserDetails getUser() {
        // 从全局SecurityContextHolder中获取Authentication找到SysUserDetails进行返回
        // 可以通过 SysUserDetails 获取到 用户ID 等自定义信息
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof SysUserDetails) {
                return (SysUserDetails) authentication.getPrincipal();
            }
        }
        return null;
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户ID
     *
     * @return
     */
    public static Long getUserId() {
        return Convert.toLong(Objects.requireNonNull(getUser()).getUserId());
    }

    /**
     * 获取角色信息
     *
     * @return
     */
    public static Set<String> getRoles() {
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            // 去除 "ROLE_" 返回给前端
            if (CollectionUtil.isNotEmpty(authorities)) {
                Set<String> roles = authorities.stream().filter(item -> item.getAuthority().startsWith("ROLE_"))
                        .map(item -> StrUtil.removePrefix(item.getAuthority(), "ROLE_"))
                        .collect(Collectors.toSet());
                return roles;
            }
        }
        // 无 ，返回空
        return Collections.emptySet();
    }
}
